package com.puff.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.puff.constant.MessageConstant;
import com.puff.dto.UserDTO;
import com.puff.dto.UserLoginDTO;
import com.puff.dto.UserPageQueryDTO;
import com.puff.entity.User;
import com.puff.exception.LoginFailedException;
import com.puff.mapper.UserMapper;
import com.puff.properties.WeChatProperties;
import com.puff.result.PageResult;
import com.puff.service.UserService;
import com.puff.utils.HttpClientUtil;
import com.puff.vo.ShopVO;
import com.puff.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    // 微信服务接口地址
    private static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    /**
     * 微信用户登录
     * @param userLoginDTO
     * @return
     */
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //调用微信接口服务，获得当前微信用户的openid
        String openid = getOpenid(userLoginDTO.getCode());
        // 判断openid是否为空，如果为空，则表示登录失败，抛出业务异常
        if (openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        // 判断当前用户是否为新用户
        User user = userMapper.getByOpenid(openid);
        // 如果是新用户，自动完成注册
        if (user == null){
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }
        // 返回用户对象
        return user;
    }

    /**
     * 用户列表分页查询
     * @param userPageQueryDTO
     * @return
     */
    public PageResult pageQuery(UserPageQueryDTO userPageQueryDTO) {
        // 利用PageHelper进行分页查询的参数计算
        PageHelper.startPage(userPageQueryDTO.getPage(),userPageQueryDTO.getPageSize());

        // 动态获取查询条件（员工名称），进行条件查询
        Page<UserVO> page = userMapper.pageQuery(userPageQueryDTO);

        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 批量删除用户信息
     * @param ids
     */
    public void deleteBatch(List<Long> ids) {
        userMapper.deleteByIds(ids);
    }

    /**
     * 根据id查询用户信息
     * @param id
     * @return
     */
    public UserVO getUserById(Long id) {
        User user = userMapper.getById(id);

        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user,userVO);

        return userVO;
    }

    /**
     * 修改用户信息
     * @param userDTO
     */
    public void updateUser(UserDTO userDTO) {
        User user = new User();

        BeanUtils.copyProperties(userDTO,user);
        userMapper.update(user);
    }

    /**
     * 调用微信接口服务，获得当前微信用户的openid
     * @param code
     * @return
     */
    private String getOpenid(String code){
        // 调用微信接口服务，获得当前微信用户的openid
        Map<String, String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, map);

        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");

        return openid;
    }
}
